<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button v-auth="Permission.IMPORT" type="primary" @click="handleCreate"> 导入 </a-button>
        <a-button v-auth="Permission.DOWNLOAD" @click="handleDownload"> 下载 </a-button>
        <a-button v-auth="Permission.DEL" type="error" @click="handleBatchDelete"> 删除 </a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'formType'">
          {{ formatDictValue(formTypeDicts, record.formType) }}
        </template>
        <template v-else-if="column.key === 'formLayout'">
          {{ formatDictValue(formLayoutDicts, record.formLayout) }}
        </template>
        <template v-else-if="column.key === 'extendBaseEntity'">
          {{ formatDictValue(extendBaseEntityDicts, record.extendBaseEntity) }}
        </template>
        <template v-else-if="column.key === 'action'">
          <TableAction :actions="createActions(record)" />
        </template>
      </template>
    </BasicTable>
    <ImportDrawer @register="registerImportDrawer" @success="handleSuccess" />
    <UpdateDrawer @register="registerUpdateDrawer" @success="handleSuccess" />
  </div>
</template>

<script lang="ts" setup>
import { onBeforeMount, ref } from 'vue';
import {
  BasicTable,
  useTable,
  TableAction,
  ActionItem,
  EditRecordRow,
} from '/@/components/Table';
import { getGenTablePage, delGenTable, download, batchDelGenTable } from '/@/api/sys/gen';
import { getDictDetailListApi } from '/@/api/sys/dict';
import { Permission, columns, searchFormSchema } from './index-option';
import { useDrawer } from '/@/components/Drawer';
import ImportDrawer from './import-drawer.vue';
import UpdateDrawer from './update-drawer.vue';
import { useMessage } from '/@/hooks/web/useMessage';
import { formatDictValue } from '/@/utils';
import { downloadByData } from '/@/utils/file/download';

const formTypeDicts = ref([]);
const formLayoutDicts = ref([]);
const extendBaseEntityDicts = ref([]);
onBeforeMount(async () => {
  const formTypeResult = await getDictDetailListApi({ code: 'form_type' });
  const formLayoutResult = await getDictDetailListApi({ code: 'form_layout' });
  const extendBaseEntityResult = await getDictDetailListApi({ code: 'yes_no' });
  formTypeDicts.value = formTypeResult.data;
  formLayoutDicts.value = formLayoutResult.data;
  extendBaseEntityDicts.value = extendBaseEntityResult.data;
});

const [registerTable, { reload, getSelectRowKeys }] = useTable({
  title: '代码生成',
  api: getGenTablePage,
  rowKey: 'tableId',
  columns,
  formConfig: {
    labelWidth: 80,
    schemas: searchFormSchema,
  },
  rowSelection: { type: 'checkbox' },
  useSearchForm: true,
  bordered: true,
  canResize: true,
  ellipsis: true,
  actionColumn: {
    width: 220,
    title: '操作',
    dataIndex: 'action',
    fixed: 'right',
  },
});

const [registerImportDrawer, { openDrawer: openImportDrawer }] = useDrawer();
const [registerUpdateDrawer, { openDrawer: openUpdateDrawer }] = useDrawer();

const { createMessage, createConfirm } = useMessage();

function handleCreate() {
  openImportDrawer(true);
}

function handleEdit(record: Recordable) {
  openUpdateDrawer(true, { record });
}

function handleDelete(record: Recordable) {
  delGenTable(record.tableId).then((res) => {
    createMessage.success(res.msg);
    handleSuccess();
  });
}

function handleDownload(record) {
  let param;
  if (record && record.tableId) {
    param = { tableIds: [record.tableId] };
  } else {
    const selectedKeys = getSelectRowKeys();
    if (selectedKeys.length < 1) {
      createMessage.error('请至少选择1张表');
      return false;
    }
    if (selectedKeys.length > 20) {
      createMessage.error('最多选择20张表');
      return false;
    }
    param = { tableIds: selectedKeys };
  }
  download(param).then((res) => {
    const blob = res.data;
    const headerFilename = res.headers['content-disposition'].split(';')[1].split('=')[1];
    const filename = decodeURIComponent(escape(headerFilename));
    downloadByData(blob, filename);
    createMessage.success('代码下载成功');
  });
}

function handleBatchDelete() {
  const selectedKeys = getSelectRowKeys();
  if (selectedKeys.length < 1) {
    createMessage.error('请至少选择1张表');
    return false;
  }
  createConfirm({
    iconType: 'warning',
    title: '提示',
    content: '请确认是否删除选中的表',
    onOk: async () => {
      batchDelGenTable({ tableIds: selectedKeys }).then((res) => {
        createMessage.success(res.msg);
        handleSuccess();
      });
    },
  });
}

function handleSuccess() {
  reload();
}

function createActions(record: EditRecordRow): ActionItem[] {
  return [
    {
      icon: 'clarity:note-edit-line',
      label: '编辑',
      auth: Permission.EDIT,
      onClick: handleEdit.bind(null, record),
    },
    {
      icon: 'ant-design:download-outlined',
      label: '下载',
      auth: Permission.DOWNLOAD,
      onClick: handleDownload.bind(null, record),
    },
    {
      icon: 'ant-design:delete-outlined',
      label: '删除',
      auth: Permission.DEL,
      color: 'error',
      popConfirm: {
        title: '是否删除业务表【' + record.tableName + '】？',
        confirm: handleDelete.bind(null, record),
      },
    },
  ];
}
</script>
